Clear() in Selenium
clear() is a Selenium WebDriver method used to remove the existing text or value from an editable web element such as a text box, username field, password field, search box, email field, textarea, or other input control.
The clear() method is especially useful when an input field already contains data and the automation script needs to replace that data with a new value. Instead of manually selecting and deleting existing characters, Selenium can use clear() to remove the current value before entering new data with sendKeys().
Clear() is part of the Selenium WebElement interaction methods used while automating web applications. Selenium WebDriver training commonly covers WebElements, browser interactions, locators, forms, waits, and automation frameworks. Learn more about Selenium Training at JustAcademy.
You can also explore the course demonstration through Register for Selenium Course Demo.
1. What is clear() in Selenium?
The clear() method removes the existing value from an editable WebElement. It is mainly used with input fields and textareas.
Basic example:
WebElement username = driver.findElement(By.id("username"));
username.clear();
If the username field contains oldUser, clear() removes that existing value from the field.
2. Basic Syntax of clear()
The basic syntax is:
element.clear();
Example:
WebElement searchBox = driver.findElement(By.id("search"));
searchBox.clear();
Here:
- element is the WebElement on which the operation is performed.
- clear() removes the existing editable value.
3. Why is clear() Used?
Automated web applications frequently contain fields that may already contain data. Before entering new test data, the old value may need to be removed.
- Replace an existing username.
- Replace an existing password.
- Clear a search field.
- Update an email address.
- Modify a phone number.
- Change an address.
- Update form information.
- Prepare fields for data-driven testing.
- Reset an input before another test iteration.
4. How clear() Works
The basic automation flow is:
Open Web Application
↓
Locate Input Element
↓
Check Existing Value
↓
Call clear()
↓
Existing Value Removed
↓
Call sendKeys()
↓
Enter New Test Data
5. clear() with ID Locator
Suppose the HTML is:
<input type="text" id="username" value="oldUser">
Selenium code:
WebElement username = driver.findElement(By.id("username"));
username.clear();
The existing value oldUser is cleared from the input field.
6. clear() with Name Locator
Example HTML:
<input type="text" name="email" value="[email protected]">
Java code:
WebElement email = driver.findElement(By.name("email"));
email.clear();
7. clear() with XPath
XPath can be used to locate the element before calling clear().
WebElement username = driver.findElement(By.xpath("//input[@id='username']"));
username.clear();
Another example:
driver.findElement(By.xpath("//input[@name='email']")).clear();
8. clear() with CSS Selector
CSS selectors can also be used.
WebElement searchBox = driver.findElement(By.cssSelector("#search"));
searchBox.clear();
Using an attribute selector:
WebElement email = driver.findElement(By.cssSelector("input[name='email']"));
email.clear();
9. clear() with sendKeys()
The most common use of clear() is together with sendKeys(). The clear() method removes the old value, and sendKeys() enters the new value.
WebElement username = driver.findElement(By.id("username"));
username.clear();
username.sendKeys("newUser");
The flow is:
Existing Value
↓
clear()
↓
Empty Field
↓
sendKeys("newUser")
↓
New Value
10. clear() vs sendKeys()
| Method | Purpose | Example |
| clear() | Removes existing input value | element.clear() |
| sendKeys() | Enters text or keyboard input | element.sendKeys("Hello") |
| click() | Clicks an element | element.click() |
11. clear() vs CTRL + A and Backspace
There are different ways to remove existing text from an input field. clear() is specifically designed for clearing the value of an editable element, while keyboard-based approaches simulate user keyboard actions.
Using clear():
element.clear();
Using CTRL + A and BACK_SPACE:
element.sendKeys(Keys.CONTROL, "a");
element.sendKeys(Keys.BACK_SPACE);
Keyboard-based clearing can be useful in specific interaction scenarios, but clear() is generally simpler when the requirement is simply to remove the current input value.
12. clear() in Login Form
Suppose a login form contains pre-filled values.
WebElement username = driver.findElement(By.id("username"));
WebElement password = driver.findElement(By.id("password"));
username.clear();
username.sendKeys("admin");
password.clear();
password.sendKeys("Admin@123");
This ensures that old values are removed before the new credentials are entered.
13. Complete Login Example
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class ClearExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com/login");
WebElement username = driver.findElement(By.id("username"));
WebElement password = driver.findElement(By.id("password"));
username.clear();
username.sendKeys("admin");
password.clear();
password.sendKeys("Admin@123");
driver.findElement(By.id("login")).click();
driver.quit();
}
}
14. clear() in Search Box
Search fields may contain a previous search term. clear() can remove it before entering a new search term.
WebElement search = driver.findElement(By.id("search"));
search.clear();
search.sendKeys("Selenium WebDriver");
This pattern is frequently useful when testing multiple search scenarios.
15. Search Box Test Flow
Open Application
↓
Locate Search Box
↓
Clear Existing Search
↓
Enter New Keyword
↓
Press ENTER
↓
Validate Search Results
Example:
WebElement search = driver.findElement(By.id("search"));
search.clear();
search.sendKeys("Laptop");
search.sendKeys(Keys.ENTER);
16. clear() in Registration Form
Registration forms can contain multiple fields. If values are already present, clear() can be used before replacing them.
WebElement firstName = driver.findElement(By.id("firstName"));
WebElement lastName = driver.findElement(By.id("lastName"));
WebElement email = driver.findElement(By.id("email"));
firstName.clear();
firstName.sendKeys("Rahul");
lastName.clear();
lastName.sendKeys("Sharma");
email.clear();
email.sendKeys("[email protected]");
17. clear() in Textarea
The clear() method can also be used with a textarea when it contains editable text.
HTML:
<textarea id="comments">Old comment</textarea>
Selenium:
WebElement comments = driver.findElement(By.id("comments"));
comments.clear();
comments.sendKeys("New comment");
18. clear() with WebElement Variable
Storing the WebElement in a variable can make the code easier to read and reuse.
WebElement emailField = driver.findElement(By.id("email"));
emailField.clear();
emailField.sendKeys("[email protected]");
19. clear() Without Creating a Variable
For simple interactions, clear() can be called directly after locating the element.
driver.findElement(By.id("username")).clear();
Or:
driver.findElement(By.id("username")).clear();
driver.findElement(By.id("username")).sendKeys("admin");
20. clear() with Explicit Wait
Dynamic applications may require synchronization before interacting with an input field.
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement username = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("username"))
);
username.clear();
username.sendKeys("admin");
The wait allows Selenium to wait until the input element is visible before performing the interaction.
21. clear() with elementToBeClickable()
In some workflows, the field must be interactable before the automation attempts to modify it.
WebElement input = new WebDriverWait(driver, Duration.ofSeconds(10))
.until(ExpectedConditions.elementToBeClickable(By.id("username")));
input.clear();
input.sendKeys("admin");
22. clear() and Dynamic Web Applications
Modern web applications may update input elements dynamically. An element that was previously located can become stale after a page update or DOM modification.
In such cases, locate the current element again before interacting with it.
WebElement input = driver.findElement(By.id("username"));
input.clear();
If the DOM has changed significantly since the element was located, reacquire the element before calling clear().
23. StaleElementReferenceException with clear()
A StaleElementReferenceException may occur when a previously located WebElement is no longer attached to the current DOM.
Example situation:
WebElement username = driver.findElement(By.id("username"));
driver.navigate().refresh();
username.clear();
The old WebElement reference may no longer represent the current element. A safer approach is to locate the element again after the page refresh.
driver.navigate().refresh();
WebElement username = driver.findElement(By.id("username"));
username.clear();
24. ElementNotInteractableException with clear()
An ElementNotInteractableException can occur when the located element cannot currently be interacted with.
Possible reasons include:
- The element is hidden.
- The element is disabled.
- The element is not ready.
- The wrong element was located.
- The element is covered or otherwise unavailable for normal interaction.
Check the element's state and application timing before calling clear().
25. InvalidElementStateException with clear()
An InvalidElementStateException can occur when an element is not in a state that supports the requested operation.
Before using clear(), verify that the element is an appropriate editable control and that the current page state allows interaction.
26. clear() with Password Field
clear() can be used with editable password fields.
WebElement password = driver.findElement(By.id("password"));
password.clear();
password.sendKeys("NewPassword@123");
The actual password value should be handled securely in real automation frameworks rather than hard-coded unnecessarily in test source code.
27. clear() with Email Field
WebElement email = driver.findElement(By.id("email"));
email.clear();
email.sendKeys("[email protected]");
28. clear() with Phone Number Field
WebElement phone = driver.findElement(By.id("phone"));
phone.clear();
phone.sendKeys("9876543210");
29. clear() with Address Field
WebElement address = driver.findElement(By.id("address"));
address.clear();
address.sendKeys("Mumbai, Maharashtra, India");
30. clear() with XPath
XPath is useful when an input does not have a convenient ID or name.
driver.findElement(
By.xpath("//input[@placeholder='Enter username']")
).clear();
Using a label relationship:
driver.findElement(
By.xpath("//input[@type='email']")
).clear();
31. clear() with Dynamic XPath
When the attribute values are dynamic, an appropriate XPath expression can be used to locate the input.
WebElement input = driver.findElement(
By.xpath("//input[contains(@placeholder,'username')]")
);
input.clear();
Another example:
WebElement search = driver.findElement(
By.xpath("//input[starts-with(@id,'search')]")
);
search.clear();
32. clear() with CSS Selector
WebElement username = driver.findElement(
By.cssSelector("input#username")
);
username.clear();
Attribute selector:
WebElement email = driver.findElement(
By.cssSelector("input[name='email']")
);
email.clear();
33. clear() with Page Object Model
In a Page Object Model framework, clear() can be encapsulated inside reusable page methods.
public class LoginPage {
private WebDriver driver;
private By username = By.id("username");
private By password = By.id("password");
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public void enterUsername(String value) {
WebElement element = driver.findElement(username);
element.clear();
element.sendKeys(value);
}
public void enterPassword(String value) {
WebElement element = driver.findElement(password);
element.clear();
element.sendKeys(value);
}
}
Test usage:
LoginPage loginPage = new LoginPage(driver);
loginPage.enterUsername("admin");
loginPage.enterPassword("Admin@123");
34. Reusable Clear and Enter Method
A reusable utility method can combine clear() and sendKeys().
public void clearAndEnter(By locator, String value) {
WebElement element = driver.findElement(locator);
element.clear();
element.sendKeys(value);
}
Usage:
clearAndEnter(By.id("username"), "admin");
clearAndEnter(By.id("email"), "[email protected]");
35. clear() in Data-Driven Testing
When multiple sets of test data are used, the same input field may need to be cleared before each new value is entered.
String[] usernames = {"user1", "user2", "user3"};
WebElement username = driver.findElement(By.id("username"));
for (String value : usernames) {
username.clear();
username.sendKeys(value);
}
This pattern can be useful when multiple test iterations use the same form.
36. clear() with TestNG DataProvider
@DataProvider(name = "userData")
public Object[][] userData() {
return new Object[][] {
{"[email protected]"},
{"[email protected]"},
{"[email protected]"}
};
}
@Test(dataProvider = "userData")
public void emailTest(String emailValue) {
WebElement email = driver.findElement(By.id("email"));
email.clear();
email.sendKeys(emailValue);
}
37. clear() in E-Commerce Testing
Consider an e-commerce search field containing an existing product name.
WebElement search = driver.findElement(By.id("search"));
search.clear();
search.sendKeys("Laptop");
search.sendKeys(Keys.ENTER);
Possible flow:
Existing Search Term
↓
clear()
↓
Empty Search Field
↓
Enter "Laptop"
↓
Press ENTER
↓
Display Search Results
38. clear() in Checkout Testing
Checkout forms may contain editable customer information.
WebElement phone = driver.findElement(By.id("phone"));
phone.clear();
phone.sendKeys("9876543210");
WebElement address = driver.findElement(By.id("address"));
address.clear();
address.sendKeys("Mumbai, Maharashtra");
39. clear() in Profile Update Testing
Profile update pages commonly display previously saved information.
WebElement firstName = driver.findElement(By.id("firstName"));
firstName.clear();
firstName.sendKeys("Amit");
WebElement email = driver.findElement(By.id("email"));
email.clear();
email.sendKeys("[email protected]");
40. clear() and Iframes
If the input field is located inside an iframe, Selenium must switch to the iframe before locating and clearing the field.
driver.switchTo().frame("profileFrame");
WebElement email = driver.findElement(By.id("email"));
email.clear();
email.sendKeys("[email protected]");
driver.switchTo().defaultContent();
The correct sequence is:
Switch to iframe
↓
Locate Input
↓
clear()
↓
sendKeys()
↓
Perform Required Action
↓
Return to Main Document
41. clear() and Multiple Windows
If the input field belongs to another browser window or tab, switch to that window before locating the element.
String parentWindow = driver.getWindowHandle();
for (String window : driver.getWindowHandles()) {
if (!window.equals(parentWindow)) {
driver.switchTo().window(window);
break;
}
}
WebElement input = driver.findElement(By.id("username"));
input.clear();
input.sendKeys("admin");
42. clear() and Shadow DOM
Some modern applications use Shadow DOM. If the target input is inside a shadow root, normal page-level locators may not directly locate it. The appropriate Shadow DOM access method must be used before interacting with the input.
43. clear() and Read-Only Inputs
A read-only input is not intended to be edited by normal user interaction.
<input type="text" id="username" readonly value="admin">
Calling clear() on a read-only element may fail because the element does not permit normal editing. The test should follow the application's intended workflow for changing the value.
44. clear() and Disabled Inputs
Disabled fields cannot normally be edited.
<input type="text" id="username" disabled value="admin">
Attempting to clear a disabled field can result in an interaction-related exception. The automation should first verify whether the field is expected to become enabled through a user action.
45. clear() with JavaScript
In normal Selenium automation, clear() should generally be preferred for standard editable fields. JavaScript-based manipulation changes the DOM directly and may not reproduce the same browser interaction as a real user.
Example of JavaScript value manipulation:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(
"arguments[0].value='';",
element
);
This approach should be used carefully because directly changing a DOM property may not trigger all application events that would normally occur during user interaction.
46. clear() vs JavaScript Value Change
| Approach | Purpose | Typical Use |
| clear() | Clear an editable WebElement value | Normal Selenium form automation |
| sendKeys() | Enter keyboard input | Normal user-like text entry |
| JavaScript | Directly manipulate DOM properties | Special cases and troubleshooting |
| CTRL + A + BACK_SPACE | Keyboard-based clearing | Specific keyboard interaction scenarios |
47. Common Exceptions with clear()
| Exception | Possible Reason |
| NoSuchElementException | The element could not be located |
| ElementNotInteractableException | The element cannot currently receive interaction |
| InvalidElementStateException | The element is not in a valid state for clearing |
| StaleElementReferenceException | The WebElement reference is no longer attached to the current DOM |
| TimeoutException | Expected condition was not satisfied within the wait period |
48. NoSuchElementException
If Selenium cannot find the input element, clear() cannot be executed.
Check:
- Locator correctness.
- Current URL.
- Page source.
- Iframe context.
- Dynamic loading.
- Whether the element has been replaced.
49. TimeoutException
When explicit waits are used, TimeoutException can occur if the required condition is not satisfied within the specified time.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement input = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("username"))
);
input.clear();
If the element does not become visible within the timeout, the wait can fail.
50. Best Practices for clear()
- Use clear() when an existing input value needs to be removed.
- Use stable locators to identify input fields.
- Use explicit waits for dynamically loaded elements.
- Verify that the element is editable before clearing it.
- Use clear() before sendKeys() when replacing existing data.
- Re-locate elements after page refreshes or significant DOM changes.
- Use Page Object Model for reusable form interactions.
- Keep test data separate from automation logic.
- Avoid unnecessary JavaScript manipulation.
- Handle iframe context correctly.
- Use meaningful test data in data-driven automation.
- Validate the resulting value after important form interactions.
51. Common Mistakes While Using clear()
- Calling clear() on a non-editable element.
- Using an incorrect locator.
- Trying to clear a disabled input.
- Trying to clear a read-only field.
- Ignoring iframe context.
- Using a stale WebElement reference.
- Trying to interact before the field is ready.
- Using JavaScript unnecessarily.
- Not checking whether the old value was actually removed.
- Using Thread.sleep() everywhere instead of appropriate synchronization.
52. How to Verify that clear() Worked
The field value can be retrieved using getAttribute("value").
WebElement username = driver.findElement(By.id("username"));
username.clear();
String value = username.getAttribute("value");
System.out.println("Current value: " + value);
After a successful clear operation, the value should normally be empty for a standard editable input field.
53. Using Assertion After clear()
In a test framework, the cleared value can be validated with an assertion.
WebElement username = driver.findElement(By.id("username"));
username.clear();
String value = username.getAttribute("value");
Assert.assertEquals(value, "");
This confirms that the field contains an empty value after clear().
54. clear() Followed by Validation
WebElement email = driver.findElement(By.id("email"));
email.clear();
String actualValue = email.getAttribute("value");
System.out.println("Value after clear: " + actualValue);
Validation is useful when the clear operation is an important part of the test scenario.
55. Complete Practical Example
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ClearFieldExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.manage().window().maximize();
driver.get("https://example.com");
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement searchBox = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("search")
)
);
searchBox.clear();
searchBox.sendKeys("Selenium WebDriver");
} finally {
driver.quit();
}
}
}
56. Real-World Form Automation Example
Consider an employee profile update page containing existing information.
WebElement firstName = driver.findElement(By.id("firstName"));
WebElement lastName = driver.findElement(By.id("lastName"));
WebElement email = driver.findElement(By.id("email"));
WebElement phone = driver.findElement(By.id("phone"));
firstName.clear();
firstName.sendKeys("Amit");
lastName.clear();
lastName.sendKeys("Kumar");
email.clear();
email.sendKeys("[email protected]");
phone.clear();
phone.sendKeys("9876543210");
This pattern allows the automation script to replace the existing profile information with new test data.
57. clear() in a Reusable Utility Class
Large Selenium frameworks can contain reusable utility methods for common WebElement operations.
public class ElementUtils {
private WebDriver driver;
public ElementUtils(WebDriver driver) {
this.driver = driver;
}
public void clearField(By locator) {
WebElement element = driver.findElement(locator);
element.clear();
}
public void clearAndType(By locator, String value) {
WebElement element = driver.findElement(locator);
element.clear();
element.sendKeys(value);
}
}
Usage:
ElementUtils utils = new ElementUtils(driver);
utils.clearField(By.id("username"));
utils.clearAndType(By.id("email"), "[email protected]");
58. Practical Test Scenario
Scenario: Verify that a user can replace an existing search term.
- Launch the browser.
- Open the application.
- Locate the search field.
- Verify that the field contains an existing value.
- Call clear().
- Enter a new search keyword using sendKeys().
- Submit the search.
- Verify the search results.
Example:
WebElement search = driver.findElement(By.id("search"));
search.clear();
search.sendKeys("Laptop");
search.sendKeys(Keys.ENTER);
59. Advantages of clear()
- Simple and readable syntax.
- Useful for replacing existing input data.
- Works naturally with sendKeys().
- Useful in repetitive form automation.
- Supports reusable Page Object Model methods.
- Useful for data-driven testing.
- Reduces the need for manual keyboard deletion sequences.
60. Limitations and Considerations
- The target must be an appropriate editable element.
- Disabled fields cannot normally be edited.
- Read-only fields are not intended for normal modification.
- Dynamic applications may require synchronization.
- Elements inside iframes require correct frame switching.
- Stale references may need to be reacquired.
- Application-specific controls may require a different interaction strategy.
61. Interview Questions on clear()
Q1. What is clear() in Selenium?
clear() is a WebElement method used to remove the existing value from an editable web element.
Q2. Which interface provides clear()?
The clear() method is provided by Selenium's WebElement interface.
Q3. How do you clear a textbox in Selenium?
driver.findElement(By.id("username")).clear();
Q4. Can clear() be used with a textarea?
Yes. It can be used with an editable textarea.
Q5. What is the difference between clear() and sendKeys()?
clear() removes the existing value, while sendKeys() enters text or keyboard input.
Q6. Can clear() be used on a disabled field?
A disabled field is not normally editable, so clear() may result in an interaction-related exception.
Q7. How do you clear a field and enter a new value?
element.clear();
element.sendKeys("New Value");
Q8. What exception can occur if an element becomes invalid after a DOM update?
A StaleElementReferenceException can occur when the previously located WebElement is no longer attached to the current DOM.
Q9. How can you verify that clear() removed the value?
String value = element.getAttribute("value");
Q10. Can clear() be used with XPath?
Yes. XPath can be used to locate the WebElement and clear() can then be called on it.
62. Quick Reference
| Requirement | Example |
| Clear field | element.clear(); |
| Clear and enter text | element.clear(); element.sendKeys("Hello"); |
| Clear using ID | driver.findElement(By.id("email")).clear(); |
| Clear using Name | driver.findElement(By.name("email")).clear(); |
| Clear using XPath | driver.findElement(By.xpath("//input[@id='email']")).clear(); |
| Clear using CSS | driver.findElement(By.cssSelector("#email")).clear(); |
| Get current value | element.getAttribute("value"); |
| Clear with explicit wait | wait.until(ExpectedConditions.visibilityOfElementLocated(locator)).clear(); |
63. Clear() Best-Practice Checklist
- Locate the correct input element.
- Use a stable locator.
- Confirm that the element is editable.
- Use explicit waits when the application is dynamic.
- Use clear() before sendKeys() when replacing existing data.
- Re-locate elements after page refreshes or DOM replacements.
- Use Page Object Model for reusable form operations.
- Keep test data separate from automation code.
- Validate important clearing operations.
- Handle iframe context correctly.
- Avoid unnecessary JavaScript-based value manipulation.
- Use clear() as part of reusable automation utilities where appropriate.
64. Difference Between clear(), sendKeys(), and click()
| Method | Main Purpose | Example |
| clear() | Remove existing input value | element.clear(); |
| sendKeys() | Enter text or keyboard input | element.sendKeys("Selenium"); |
| click() | Perform a mouse click | element.click(); |
65. Conclusion
The clear() method is an important Selenium WebDriver method for removing existing values from editable web elements. It is commonly used before entering new test data into usernames, passwords, search fields, email fields, textareas, registration forms, checkout forms, and profile update fields.
The most common pattern is:
element.clear();
element.sendKeys("New Value");
For reliable automation, clear() should be combined with correct locators, appropriate waits, proper iframe handling, reusable Page Object Model methods, and suitable test data management. Understanding clear() along with sendKeys(), WebElement methods, and Selenium synchronization techniques is important for building maintainable browser automation tests.
Course Resource: Selenium Training Course
Demo Registration: Register for Course Demo